package com.example.educationalsystem.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.educationalsystem.common.util.DateFormates;
import com.example.educationalsystem.common.util.ExcelListener;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.entity.Course;
import com.example.educationalsystem.entity.Score;
import com.example.educationalsystem.entity.Vo.CourseVo;
import com.example.educationalsystem.service.ICourseService;
import com.example.educationalsystem.service.IScoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static ch.qos.logback.core.joran.action.ActionConst.NULL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zpc
 * @since 2022-12-02
 */
@Api(value = "/course",tags = "课程信息管理")
@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private ICourseService iCourseService;

    @GetMapping("/getAllCourse")
    @ApiOperation(value = "获取所有课程信息",notes = "获取所有课程信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getAllCourse()
    {
        ResponseJson responseJson=new ResponseJson();
        List<CourseVo> courselist=iCourseService.getAllCourse();
        System.out.println(courselist.toString());
        if(courselist!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(courselist);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，暂无信息！");
        }
        return responseJson;

    }
    @GetMapping("/getCoursePage")
    @ApiOperation(value = "获取课程分页信息",notes = "获取课程分页信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getCoursePage(@RequestParam(value = "size", defaultValue = "10") long size,
                                      @RequestParam(value = "current", defaultValue = "1") long current,
                                      String teacherId,String classroomId
                                      )
    {
        ResponseJson responseJson=new ResponseJson();
        Page<CourseVo>  page=new Page<>(current,size);
        QueryWrapper<CourseVo> queryWrapper=new QueryWrapper<>();
        if(teacherId==null&&classroomId==null)
        {
            queryWrapper=null;
        }
        if(teacherId!=null)
        {
            queryWrapper.eq("b.teacher_id",teacherId);
        }

        Page<CourseVo> courseVoPage=iCourseService.getCoursePage(page,queryWrapper);
        System.out.println(courseVoPage.toString());
        if(courseVoPage!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(courseVoPage);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，暂无信息！");
        }
        return responseJson;

    }
    @ApiOperation(value = "导出课程信息",notes = "导出课程信息")
    @ResponseBody
    @GetMapping("Download")
    public void myDownload(HttpServletResponse response,@RequestParam String tableName) throws IOException {

       try{
           response.setContentType("application/vnd.ms-excel");
           response.setCharacterEncoding("utf-8");
           response.setHeader("Content-disposition", "attachment;filename="+ new String(tableName.getBytes(StandardCharsets.UTF_8),"ISO8859-1")+".xls");
           System.out.println(iCourseService.getAllCourse().toString());
           EasyExcel.write(response.getOutputStream(), CourseVo.class).sheet(tableName).doWrite(iCourseService.getAllCourse());
       }catch(Exception e)
       {
           response.reset();
       }


    }
    @ApiOperation(value = "导入课程信息",notes = "导入课程信息")
    @ResponseBody
    @PostMapping("Import")
    public ResponseJson myImport(MultipartFile file) {
        ResponseJson responseJson=new ResponseJson();
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, Course.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            System.out.println(list.size());
            if (list.size() >= 1) {
                for (int i = 0; i < list.size(); i++) {
                    Course course = (Course) list.get(i);
                    System.out.println(course.toString());

                    //使用mybatis-plus添加到数据库
                    Boolean res=iCourseService.save(course);
                    if(res)
                    {
                        responseJson.setStatus(200);
                        responseJson.setMsg("导入成功！");
                    }
                    else {
                        responseJson.setStatus(400);
                        responseJson.setMsg("导入失败！");
                    }
                    System.out.println(res);
                }
            }

        } catch (Exception e) {
            responseJson.setStatus(400);
            responseJson.setMsg(e.toString());
            e.printStackTrace();
        }

        return responseJson;
    }



    @ApiOperation(value = "增加课程信息",notes = "增加一条课程信息记录")
    @PostMapping("/insertCourse")
    @ResponseBody
    public ResponseJson insertCourse(@RequestBody Course requestCourse )
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        String strID = DateFormates.NowDateFormate();
        requestCourse.setCourseId(strID.substring(8));
        System.out.println(requestCourse.getCourseId());
        requestCourse.setCourseActualCount(0);
        Course courseOne=iCourseService.getBaseMapper().selectOne(queryWrapper.eq("course_id",requestCourse.getCourseId()));
        if(courseOne==null)
        {
            Boolean result=iCourseService.save(requestCourse);
            if(result)
            {
                responseJson.setMsg("增加成功！");
                responseJson.setStatus(200);
                responseJson.setData(requestCourse);

            }
            else
            {
                responseJson.setStatus(400);
                responseJson.setMsg("增加失败！");
            }
        }
        else
        {
            responseJson.setStatus(400);
            responseJson.setMsg("该课程信息已存在！");
        }
        return responseJson;
    }


    @ApiOperation(value = "删除课程信息",notes = "根据学号，删除一条课程信息")
    @DeleteMapping("/deleteCourse")
    @ResponseBody
    public  ResponseJson deleteCourse( @ApiParam(name = "courseId", value = "课程ID", required = true) @RequestParam String courseId)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        Course courseOne=iCourseService.getBaseMapper().selectOne(queryWrapper.eq("course_id",courseId));
        if(courseOne!=null)
        {
            int result=iCourseService.getBaseMapper().deleteById(courseOne.getCourseId());
            System.out.println(result);
            if(result==1)
            {
                responseJson.setData(courseOne);
                responseJson.setMsg("删除成功！");
                responseJson.setStatus(200);
            }
            else
            {
                responseJson.setMsg("删除失败");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("该课程信息不存在！");
        }
        return responseJson;

    }
    @ApiOperation(value = "批量删除课程信息",notes = "根据课程编号，删除多条课程信息")
    @DeleteMapping("/deleteCourses")
    @ResponseBody
    public  ResponseJson deleteCourses( @ApiParam(name = "courseIds", value = "课程IDs", required = true) @RequestParam String courseIds)
    {
        ResponseJson responseJson=new ResponseJson();
        String[] idArr = courseIds.split(",");
        List<String> idList = Arrays.asList(idArr);
        boolean result=iCourseService.removeByIds(idList);
        System.out.println(result);
        if(result)
        {
//            responseJson.setData(courseOne);
            responseJson.setMsg("批量删除成功！");
            responseJson.setStatus(200);
        }
        else
        {
            responseJson.setMsg("批量删除失败");
            responseJson.setStatus(400);
        }
        return responseJson;

    }

    @ApiOperation(value = "更新课程信息",notes = "更新课程信息，必须填写课程ID")
    @PutMapping("/updateCourse")
    @ResponseBody
    public ResponseJson updateCourse(@RequestBody  Course resquestCourse)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("course_id",resquestCourse.getCourseId());
        Course courseOne=iCourseService.getBaseMapper().selectOne(queryWrapper);
        if(courseOne!=null)
        {
            int result=iCourseService.getBaseMapper().update(resquestCourse,queryWrapper);
            if(result==1)
            {
                responseJson.setMsg("更新成功！");
                responseJson.setStatus(200);
                responseJson.setData(iCourseService.getBaseMapper().selectOne(queryWrapper));
            }
            else {
                responseJson.setMsg("更新失败！");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setMsg("该课程信息不存在");
            responseJson.setStatus(404);
        }
        return responseJson;
    }
}

